package com.zt.securityTest.handler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.zt.securityTest.common.R;
import com.zt.securityTest.exception.CustomerAuthenticationException;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.authentication.*;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import static com.zt.securityTest.common.ResultCode.*;
/**
 * 自定义认证失败处理器
 * 用户认证校验失败的处理器（登录时的报错处理）
 * time: 2024.11.26 17.17
 */
@Component
public class LoginFailureHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        //设置客户端的响应的内容类型
        response.setContentType("application/json;charset=UTF-8");
        //获取输出流
        ServletOutputStream outputStream = response.getOutputStream();
        String message = null;//提示信息
        int code = LOGIN_FAILURE.getCode();
        //判断异常类型
        if (exception instanceof AccountExpiredException){
            message = "账户过期，登录失败！";
        } else if (exception instanceof BadCredentialsException) {
            message = "用户名或密码错误，登录失败！";
        }else if (exception instanceof CredentialsExpiredException){
            message = "密码过期，登录失败！";
        }else if (exception instanceof DisabledException){
            message = "账户被禁用，登录失败！";
        }else if (exception instanceof LockedException){
            message = "账户被锁，登录失败！";
        }else if (exception instanceof InternalAuthenticationServiceException){
            message = "账户不存在，登录失败！";
        }else if (exception instanceof CustomerAuthenticationException){
           message = exception.getMessage();
           code = TOKEN_FAILURE.getCode();
        }else {
            message = "登录失败！";
        }

        //将错误信息转换成JSON
        String result = JSON.toJSONString(R.error().code(code).message(message),
                SerializerFeature.DisableCircularReferenceDetect);
        outputStream.write(result.getBytes(StandardCharsets.UTF_8));
        outputStream.flush();
        outputStream.close();
    }
}
